/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nio_server;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 *
 * @author Teva
 */
public class NIO_Server {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        int port = 2000;
        
        ServerSocket server_socket;
        
        DataInputStream input;
      
	try 
        {
	    
	    server_socket = new ServerSocket(port);
            
	    System.out.println("Server waiting for client on port " +  server_socket.getLocalPort());
	    
	    // server infinite loop
	    while(true) 
            {		
                    
                Socket socket = server_socket.accept();
                                		
                System.out.println("New connection accepted " +   socket.getInetAddress() +  ":" + socket.getPort());
                
		input = new DataInputStream(socket.getInputStream()); 
		
              
                //Printing the received data
                 Scanner socketReader = new Scanner(socket.getInputStream());

                   while(socketReader.hasNext())
                     {
                          //Reading the content of the socket input stream.
                         System.out.println(socketReader.nextLine());             
                       
                     }
                
                
                //print received data 
		try 
                {
		    byte[] byteArray = new byte[4096];
                    
		   while(true) 
                   {
		    	int nread = input.read(byteArray , 0, 4096);
                                              
		    	if (0==nread) 
		    		break;           
		    }
                   
                 }
                                 
		catch (IOException e)
                {
		    System.out.println(e);
		}
                finally
                {
                    socket.close();
                    System.out.println("Connection closed by client");
                }
				
	    }
        }
	catch (IOException e) 
        {
	    System.out.println(e);
	}
    }
}
